<template>
  <div>
    <el-dialog :visible.sync="dialog" @close="onClose" title="修改密码" width="35%">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="密码" prop="oldPassword">
          <el-input v-model="formData.oldPassword" placeholder="请输入密码" clearable show-password :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入新密码" clearable show-password :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input v-model="formData.password2" placeholder="请输入确认密码" clearable show-password :style="{width: '100%'}">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    isEmpty
  } from '@/utils/validate'
  import {
    updatePassword
  } from '@/api/login.js'
  import {
    md5
  } from '@/utils/MD5'

  export default {
    data() {
      const validatePassword2 = (rule, value, callback) => {
        if (isEmpty(value)) {
          callback(new Error('请输入确认密码'))
        } else if (value != this.formData.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      };

      return {
        dialog: false,
        formData: {
          oldPassword: undefined,
          password: undefined,
          password2: undefined,
        },
        rules: {
          oldPassword: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
          }],
          password2: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword2
          }],
        },
      }
    },
    methods: {
      open() {
        this.dialog = true;
      },
      close() {
        this.dialog = false;
      },
      onClose() {
        this.$refs['elForm'].resetFields()
      },

      handelConfirm() {
        this.$refs['elForm'].validate(async valid => {
          if (!valid) return
          var params = {
            oldPass: md5(this.formData.oldPassword),
            newPass: md5(this.formData.password)
          };
          var res = await updatePassword(params);
          this.$utils.showSuccessMessage(res.msg, () => {
            this.close()
          })
        })
      },
    }
  }
</script>
<style>
  .el-form-item {
      margin-bottom: 22px !important;
  }
</style>
